package com.terra;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Method;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;
import android.widget.Toast;

public class ImportTC extends terraDroid {

	Document docs;
    String html = "<html><body>";

	public ImportTC() {

   Log.d("Debug", "Getting content");
   
   Connection.Response res;
   Document doc2;
   
try {
	Log.d("Debug", "Connecting");
	res = Jsoup.connect("http://www.terracaching.com/forums/login.php")
	   .data("username", Globals.strUsername, "password", Globals.strPassword, "login", "Log in")
	   .method(Method.POST)
	   .timeout(20000)
	   .execute();

	Log.d("Debug", "Parsing");
	
	Map<String, String> cookies = res.cookies();
	for (Entry<String, String> cookie : cookies.entrySet()) {
		Log.d("Debug", "Cookie->"+cookie.getKey() +":"+ cookie.getValue());
	}


	Connection connection = Jsoup.connect("http://www.terracaching.com/tdl.cgi");

	connection.data("C", "WTCBAC", "NF", "1", "CC", "-1", "SC", "-1", "PC", "-1", "CLATNS", "1", "CLATD", "00", "CLATM", "00.000", "CLONEW", "-1", "CLOND", "000", "CLONM", "00.000");
	connection.timeout(20000);
	
	for (Entry<String, String> cookie : cookies.entrySet()) {
	    connection.cookie(cookie.getKey(), cookie.getValue());
	}

	doc2 = connection.get();
	
	String text = doc2.body().text();
	Log.d("Debug", "Text->"+text);

	Elements divs = doc2.select("tr[class^=row]");
	int nCount = 0;
	divs.remove(0);
	
	for (Element div : divs) {
	    Log.d("Debug", nCount + "->" + div);
	    nCount++;
	    Elements data = div.select("td");
		int nTDCount = 0;
	    for (Element td : data) {
	    	Log.d("Debug", "--- "+nTDCount+"->"+td.text());
	    }
	    Elements link = div.select("a[href^=viewcache.cgi]");
		nTDCount = 1;
	    for (Element lnk : link) {
	    	Log.d("Debug", "--- "+nTDCount+"->"+lnk.attributes()+"("+lnk.text()+")");
	    }
	    link = div.select("a[href^=profile.cgi]");
		nTDCount = 2;
	    for (Element lnk : link) {
	    	Log.d("Debug", "--- "+nTDCount+"-> ("+lnk.text()+")");
	    }
	}

	
} catch (IOException e) {
	Log.d("Debug", "Error logging in");
	Toast toast = Toast.makeText(this, "Error accessing TC.COM?", Toast.LENGTH_LONG);
	toast.show();
	e.printStackTrace();
}

	


	}	
}
